<template>
 <div class="container">
    <div class="record-wrap">
      <div class="record-header">
        <el-button type="primary" size="mini" @click="add">新增</el-button>
        <el-button type="success" size="mini" @click="edit">编辑</el-button>
        <el-button type="danger" size="mini" @click="handleDelete">删除</el-button>
        <el-button type="primary" size="mini" @click="treeDiagnose">诊断</el-button>
      </div>
      <div class="record-list">
        <el-tree :data="recordList" :props="defaultProps" @node-click="handleNodeClick" :default-expand-all="true">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span v-if="data.id !== '-1'" class="blue">{{ data.score ? '(已评分)': '(未评分)' }}</span>
          </span>
        </el-tree>
        <el-tree :data="recordReportList" :props="defaultProps2" @node-click="handleReportNodeClick" :default-expand-all="true">
        </el-tree>
      </div>
    </div>
    <!-- 诊断记录详情 -->
    <div class="record-info" v-if="currentNode && flag === 'one'">
      <div class="inquery-view-wrap">
        <el-tabs type="border-card">
          <el-tab-pane label="基本信息">
            <div class="title" v-if="isShow">评分</div>
            <div class="content" v-if="isShow">
              <el-rate
                :disabled="isScore"
                @change="handleScore"
                v-model="score"
                :max="10"
                show-score
                text-color="#ff9900">
              </el-rate>
            </div>
            <div class="title">基本信息</div>
            <div class="content">
              <el-row :gutter="20">
                <span class="label">病人主诉:</span>
                <span class="name">{{ mainInfo.description }}</span>
              </el-row>
              <!-- <el-row :gutter="20">
                <span class="label">图片:</span>
                <span class="name">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="mainInfo.descriptionFile"
                    :preview-src-list="srcList">
                  </el-image>
                </span>
              </el-row> -->
              <!-- 症状 -->
              <div v-for="(item, index) in evaluation" :key="index">
                <div class="symptom-wrap">
                  <div  class="flex-center">
                    <div class="title">{{ getInqueryName(item.id) }}</div>
                    <div class="toggle" @click="item.toggle = !item.toggle">{{item.toggle?'折叠':'展开'}}</div>
                  </div>
                  <el-table
                    v-show="item.toggle"
                  size="small"
                  :data="item.list"
                  border
                  style="width: 100%">
                  <el-table-column
                    prop="symptomName"
                    label="症状">
                  </el-table-column>
                  <el-table-column
                    label="是否有此症狀">
                    <template slot-scope="scope">
                      <el-checkbox v-model="scope.row.check" disabled></el-checkbox>
                    </template>
                  </el-table-column>
                  </el-table>
                </div>
              </div>
              <br><br>
              <!-- 诊断结果 -->
              <el-table

                size="small"
                :data="diagnosticResult"
                border
                style="width: 100%">
                <el-table-column type="index" label="序号" width="100"/>
                <el-table-column
                  prop="content"
                  label="诊断结果">
                  <template slot-scope="scope">
                    {{scope.row.content}}
                    <!-- <el-button size="mini" @click="fuzhuCheck" style="margin-left: 20px" v-if="scope.row.content === '似为支气管哮喘，建议辅助检查'">辅助检查</el-button> -->
                  </template>
                </el-table-column>
              </el-table>
              <br><br>
              <el-table
                v-if="fuzhuList.length"
                size="small"
                :data="fuzhuList"
                border
                style="width: 100%">
                <el-table-column
                  prop="symptomName"
                  label="症状">
                </el-table-column>
                <el-table-column
                  label="是否有此症狀">
                  <template slot-scope="scope">
                    <el-checkbox v-model="scope.row.check" @change="handleChange(scope.row.check, scope.$index)"></el-checkbox>
                  </template>
                </el-table-column>
              </el-table>
              <br>
              <el-button size="mini" @click="zhenduanClick" v-if="fuzhuList.length">诊断</el-button>
              <el-button size="mini" type="primary" @click="saveClick" v-if="fuzhuList.length">保存</el-button>
            </div>
            <div class="image-list">
              <el-image
              :key="ki"
              :preview-src-list="srcList"
              v-for="(img,ki) in pictureUrl"
              style="width: 100px; height: 100px"
              :src="img"
             ></el-image>
            </div>
            <div class="title">用药</div>
            <div class="content">
              <el-row :gutter="20">
<!--                <span class="label">用药:</span>-->
                <span class="name">{{ mainInfo.medicate }}</span>
              </el-row>
<!--              <el-row :gutter="20">-->
<!--                <span class="label">医嘱:</span>-->
<!--                <span class="name">{{ mainInfo.charge }}</span>-->
<!--              </el-row>-->
            </div>
          </el-tab-pane>
          <el-tab-pane label="报告单">
            <div class="content">
              <el-tabs :tab-position="tabPosition">
                  <el-tab-pane :label="tab.reportName" v-for="(tab, index) in reportList" :key="index" >
                    <div class="report-content">
                      <div v-for="(item, index) in tab.reportData" :key="'col' + index" class="col">
                        <div v-for="(k, currentIndex) in item" :key="'cell' + currentIndex" class="cell">
                          <span v-if="k.key === 'chart'" @click="viewChat(k.key, currentIndex, tab.reportData)" style="color: #409EFF;cursor: pointer;">{{ k.value }}</span>
                          <span v-else @click="viewChat(k.key, currentIndex, tab.reportData)">{{ k.value }}</span>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
     <!-- 历史报告单 -->
    <div class="record-info" v-if="flag === 'two'">
      <el-image
        style="width: 100px; height: 100px"
        :src="reportInfoData.reportImgUrl"
        :preview-src-list="reportImgUrl">
      </el-image>
      <div class="content">
        <div class="report-content">
            <div v-for="(item, index) in reportInfoData.reportData" :key="'col' + index" class="col">
              <div v-for="(k, currentIndex) in item" :key="'cell' + currentIndex" class="cell">
                <span v-if="k.key === 'chart'" @click="viewChat(k.key, currentIndex, reportInfoData.reportData)" style="color: #409EFF;cursor: pointer;">{{ k.value }}</span>
                <span v-else @click="viewChat(k.key, currentIndex, reportInfoData.reportData)">{{ k.value }}</span>
              </div>
            </div>
        </div>
      </div>
    </div>
    <!-- 新增 -->
    <inquiryAdd ref="inquiryAdd" :title="title" :currentNode="currentNode" :patientId="patientId" @getDiagnosticListFun="getDiagnosticListFun"></inquiryAdd>
     <!-- 编辑 -->
     <inquiryEdit ref="inquiryEdit" title="编辑问诊记录" :currentNode="currentNode" :patientId="patientId" @getDiagnosticListFun="getDiagnosticListFun"></inquiryEdit>
    <!-- 折线图 -->
    <el-dialog  :visible.sync="dialogFormVisible" :append-to-body="true" width="650px"  @close="handleClose" :close-on-click-modal="false" :close-on-press-escape="false">
       <div id="myChart" :style="{width: '600px', height: '400px'}"></div>
    </el-dialog>
    <!-- 诊断 -->
    <el-dialog title="诊断" :visible.sync="diagnoseDialogVisible" width="80%" :append-to-body="true" :close-on-click-modal="false" :destroy-on-close="true">
      <treeDiagnose ref="diagnose" v-if="diagnoseDialogVisible" :reportTypeId="reportTypeId" :patientId="id">
      </treeDiagnose>
      <template slot="footer">
        <div class="dialog-footer" style="text-align: left;">
          <el-button type="primary" @click="handleDiagnose">开始诊断</el-button>
          <el-button @click="diagnoseDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
 </div>
</template>

<script>
import { getRepotinfo, delRepotinfoById, peportInfoOne,getDiagnosticList, delDiagnosticById, findDiagnostic, inquiryTableList, putScore, reportTheLineChart,getRuleType,getFuzhuCheckApi } from "@/api/infoManagement/inqueryRecord";
import inquiryAdd from './inquiryAdd.vue'
import inquiryEdit from './inquiryEdit.vue'
import treeDiagnose from "./treeDiagnose";
export default {

  data() {
    return {
      diagnoseDialogVisible: false,
      reportTypeId: '',
      dialogFormVisible: false,
      xdata: [],
      fuzhuList: [],
      defaultProps: {
        children: 'children',
        label: 'createTime',
        id: 'id'
      },
      recordList: [],
      defaultProps2: {
        children: 'childNode',
        label: 'name',
        id: 'code'
      },
      recordReportList: [],
      currentNode: null,
      title: '',
      patientId: '',
      // 详情
      inquiryOptions: [],
      mainInfo: {},
      srcList: [],
      diagnosticResult: [],
      evaluation: [],
      pictureUrl:[],
      score: 0,
      isScore: false,
      isShow: false,
      flag: '',
      reportInfoData: {},
      reportImgUrl: [],
      currentId: ''
    }
  },
  components: {inquiryAdd, inquiryEdit, treeDiagnose},
  props: {
    id: String
  },
  created() {
    this.getDiagnosticListFun()
    this.inquiryTableListFun()
  },
  methods: {
    saveClick(){
      console.log(this.mainInfo);
      let data = JSON.parse(JSON.stringify(this.mainInfo))
      if(this.diagnosticResult.length===1 && this.diagnosticResult[0].content === '支气管哮喘'){
        data.diagnosticResult = ['typical_asthma']
      }

      peportInfoOne(data).then(res=>{
        this.$message.success('保存成功')
      })
    },
    zhenduanClick(){
      let hasCheck = false
      hasCheck = this.fuzhuList.some(o=>{
        return o.check === true
      })
      if(hasCheck){
        this.diagnosticResult = [{content:'支气管哮喘'}]
      }
    },
    // 是否有症状
    handleChange(status, index) {
        this.fuzhuList[index]['check'] = status
    },
    fuzhuCheck(){
      getFuzhuCheckApi().then(res=>{
        console.log(res);
        let list = JSON.parse(JSON.stringify(res.data.data.classificationVOList))
        this.fuzhuList = []
        if (list && list.length > 0) {
          for (var i = 0; i < list.length; i++) {
            for (var j = 0; j < list[i].symptomListDTOS.length; j++) {
              this.fuzhuList .push(list[i].symptomListDTOS[j])
            }
          }
        }

      })
    },
    // 初始化左侧记录树
    getDiagnosticListFun () {
      this.isShow = false
      this.currentNode = ''
      getDiagnosticList(this.id)
       .then(res => {
        const list = res.data.data
        let list1 = list[0].data
        this.recordList = [
          {
            id: '-1',
            createTime: '诊断记录',
            score: false,
            children: list1
          }
        ]
        let list2 = list[1].data
        this.recordReportList = [
        {
            code: '-1',
            name: '历史报告单',
            identifying: '1',
            childNode: list2
          }
        ]
       })
    },
    // 获取问诊单下拉框
    inquiryTableListFun () {
      inquiryTableList()
       .then(response => {
        this.inquiryOptions = response.data.data
       })
    },
     // 获取问诊单名称
     getInqueryName(id) {
      let name = ''
      let index = this.inquiryOptions.findIndex(k => {return k.id === id})
      if (index > -1) {
        name = this.inquiryOptions[index].inquiryName
      }
      return name
    },
    // 点击诊断记录
    handleNodeClick (data) {
      this.currentNode = ''
      if (data.id !== -1) {
        this.currentNode = data.id
        this.isShow =  !data.score
        this.score = 0
        this.flag = 'one'
        this.findDiagnosticFun()
      } else {
        this.currentNode = null
      }
    },
    // 点击历史报告单
    handleReportNodeClick (data) {
      this.currentId = ''
      if (data.identifying !== '1' && data.identifying !== '2' ) {
        this.flag = 'two'
        this.currentId = data.code
        getRepotinfo(data.code, 'CHART')
         .then(response => {
            this.reportImgUrl = [response.data.data.reportImgUrl]
            this.reportInfoData = response.data.data
         })
      } else {
        this.currentId = ''
      }
    },
    // 获取详情
    findDiagnosticFun() {
      findDiagnostic(this.currentNode, 'CHART')
      .then(res => {
        let ruleTypeList = []
        getRuleType().then(r=>{
          ruleTypeList = r.data.data;
          // 诊断结果
          let diagnosticResult = []
          res.data.data.diagnosticResult.forEach(item => {
            // let name = '';
            // const node = ruleTypeList.find(o=>{
            //   return o.value === item
            // })
            // if(node){
            //   name = node.label
            // }else {
            //   item === 'doubt_asthma';
            //   name = '似为支气管哮喘，建议辅助检查'
            // }
            diagnosticResult.push({
              content: item
            })
          })
          if (res.data.data.score === -1) {
            this.score = 0
          } else {
            this.score = res.data.data.score
          }
          this.mainInfo = res.data.data
          this.srcList = [res.data.data.descriptionFile]
          this.diagnosticResult = diagnosticResult
          this.evaluation = res.data.data.evaluation
          this.pictureUrl = res.data.data.pictureUrl;
          this.evaluation.forEach(o=>{
            this.$set(o,'toggle',false)
          })
          this.reportList = res.data.data.report
        })

      })
    },

    // 新增
    add() {
      this.title = '新增问诊记录'
      this.patientId = this.id
      this.currentNode = ''
      this.$refs.inquiryAdd.dialogFormVisible = true

    },
    // 编辑
    edit() {
      if (this.currentNode) {
        this.patientId = this.id
        this.$refs.inquiryEdit.dialogFormVisible = true
      } else {
        this.$message.warning('请选择问诊记录!')
      }
    },
    // 删除
    handleDelete() {
      if (this.flag == 'one') {
        if (this.currentNode) {
            this.$confirm('确定删除问诊记录?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delDiagnosticById(this.currentNode)
              .then(() => {
                this.$message.success('删除成功')
                this.getDiagnosticListFun()
                this.currentNode = ''
                this.currentId = ''
              })
          })
        } else {
          this.title = ''
          this.$message.warning('请选择问诊记录')
        }
      } else if (this.flag == 'two') {
        if (this.currentId) {
            this.$confirm('确定删除历史报告单?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delRepotinfoById(this.currentId)
              .then(() => {
                this.$message.success('删除成功')
                this.getDiagnosticListFun()
                this.currentId = ''
                this.currentNode = ''
              })
          })
        } else {
          this.title = ''
          this.$message.warning('请选择历史报告单')
        }
      } else {
        this.$message.warning('请选择数据')
      }
    },
    // 评分
    handleScore() {
      putScore( this.currentNode, this.score)
        .then(() => {
           this.isScore =  true
           this.$message.success('成功')
           this.getDiagnosticListFun()
        })
    },
    // 查看折线图
    viewChat(key, currentIndex, data) {
      if (key === 'chart') {
        let params = {
          endTime:'',
          startTime: '',
          id: data[0][currentIndex].key
        }
        let _this = this
        reportTheLineChart(params)
         .then(res => {
          _this.dialogFormVisible = true
          _this.xdata = res.data.data.xdata
          _this.ydata = res.data.data.ydata
          if ( _this.ydata &&  _this.ydata.length > 0) {
            let yArr = []
            let leng = []
            _this.ydata.forEach(item => {
              let obj = {
                  name: item.name,
                  type:'line',
                  smooth: true,
                  data:item.values
              }
              leng.push(item.name)
              yArr.push(obj)
            })
            this.$nextTick(() => {
              //  执行echarts方法
              _this.initEcharts(yArr, leng)
            })
          }
         })
      }
    },
    // 绘制折线图
    initEcharts(yArr, leng) {
      let _this = this
      let myChart = _this.$echarts.init(document.getElementById('myChart'));
      myChart.setOption({
          legend: {
            data: leng
          },
          xAxis:  {
              type: 'category',
              data: _this.xdata
          },
          yAxis: {
              type: 'value',
              axisLabel: {
                  formatter: '{value}'
              }
          },
          series: yArr
        })
    },
    // 折线图弹窗关闭
    handleClose() {
      this.xdata = []
      this.dialogFormVisible = false
    },
    //诊断
    treeDiagnose() {
      if (this.currentNode || this.currentId) {
        this.diagnoseDialogVisible = true
      } else {
        this.$message.warning('请选择数据')
      }
    },
    // 开始诊断
    handleDiagnose() {
      debugger
      this.$refs.diagnose.diagnose()
    }
  }
}
</script>
<style scoped>
.image-list{
  margin: 20px 0;
  display: grid;
  grid-row-gap: 30px;
  grid-column-gap: 20px;
  grid-template-columns: repeat(5, 1fr);

}
.container {
  width: 100%;
  display: flex;
}
.record-wrap {
  display: inline-block;
  width: 275px;
  border: 1px solid #DCDFE6;
  padding: 8px;
  box-sizing: border-box;
}
.record-list {
   width: 100%;
   margin: 20px 0;
}
.record-name {
  width: 100%;
  height: 20px;
  line-height: 20px;
}
.record-time {
  width: 100%;
  height: 20px;
  line-height: 20px;
}
.record-info {
  display: inline-block;
  flex: 1;
  min-width: 0;
  margin-left: 20px;
  box-sizing: border-box;
}
.inquery-view-wrap {
  width: 100%;
}
.flex-center{
  display: flex;
  align-items: center;
}
.toggle{
  margin-left: 20px;
  cursor: pointer;
}
.title {
  width: 100px;
  height: 5px;
  line-height: 5px;
  overflow: hidden;
  font-size: 14px;
  color: #409EFF;
  font-weight:  bold;
  padding: 10px 0;
  border-left: 5px solid #409EFF;
  text-indent: 10px;
}
.content {
  width: 100%;
  padding: 10px 16px;
  box-sizing: border-box;
  font-size: 14px;
  overflow-x: auto;
}
.label {
  display: inline-block;
  width: 100px;
  text-align: right;
}
.name {
  display: inline-block;
  padding: 0 10px;
  box-sizing: border-box;
}
.report-content {
  width: 100%;
  display: flex;
  overflow: auto;
}
.col {
  display: inline-block;
  width: 120px;
}
.cell {
  width: 120px;
  height: 32px;
  overflow: hidden;
  text-align: left;
}
.blue {
  color: #409EFF;
  font-size: 12px;
}
</style>
